<?php
/**
 * Created by PhpStorm.
 * User: 王泽锋
 * Date: 2018/03/09
 * Time: 下午 14:23
 */

namespace app\home\controller;

use app\home\model\Shopping_address as AddressModel;
class Address extends Base
{
    /**
     * 购物地址管理主页
     */
    public function index()
    {
        $userId = session('userId');
        $AddressModel = new AddressModel();
        $map = ['create_user' => ['eq', $userId], 'status' => ['eq', 0]];
        $data = $AddressModel->get_list($map);

        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * 地址编辑页面
     */
    public function edit()
    {
        $id = input('id');
        $AddressModel = new AddressModel();
        $map = ['id' => ['eq', $id]];
        $info = $AddressModel::where($map)->find();

        $this->assign('info', $info);
        return $this->fetch();
    }


    /**
     * 添加地址页面
     */
    public function add()
    {
        if (IS_POST) {
            $data = input('post.');
            $data['create_user'] = session('userId');
            $data['create_time'] = time();
            if ($data['default_address'] == 1) {
                AddressModel::where('create_user', session('userId'))->update(['default_address' => 0]);
            }
            if (empty($data['id'])) {
                unset($data['id']);
                $info = AddressModel::where('status', 0)->insert($data);
            } else {
                $info = AddressModel::where('id', $data['id'])->update($data);
            }
            if ($info) {
                return $this->success("添加成功");
            } else {
                return $this->error("添加失败");
            }
        } else {
            return $this->fetch();
        }
    }

    /**
     * 地址删除功能
     */
    public function del()
    {
        $id = input('id');
        $data['status'] = '-1';
        $info = AddressModel::where('id', $id)->update($data);
        if ($info) {
            return $this->success("删除成功");
        } else {
            return $this->error("删除失败");
        }
    }


    /*
     * 地址功能首页设置默认
     *
     * */
    public function mr()
    {
        $id = input('id');
        $userId = session('userId');
        AddressModel::where('create_user', $userId)->update(['default_address' => 0]);
        $data['default_address'] = '1';
        $info = AddressModel::where('id', $id)->update($data);
        if ($info) {
            return $this->success("设置成功");
        } else {
            return $this->error("设置失败");
        }
    }

    
}